package net.shopxx.action.pay;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;
import net.shopxx.bean.Pager;
import net.shopxx.bean.SystemConfig;
import net.shopxx.entity.Footer;
import net.shopxx.entity.FriendLink;
import net.shopxx.entity.Member;
import net.shopxx.entity.Navigation;
import net.shopxx.entity.ProductCategory;
import net.shopxx.service.FooterService;
import net.shopxx.service.FriendLinkService;
import net.shopxx.service.MemberService;
import net.shopxx.service.NavigationService;
import net.shopxx.service.ProductCategoryService;
import net.shopxx.service.ProductService;
import net.shopxx.util.SystemConfigUtil;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

/**
 * 前台Action类 - 前台基类
 */

public class BasePayAction extends ActionSupport {

	private static final long serialVersionUID = 6718838811223344556L;

	public static final String VIEW = "view";
	public static final String LIST = "list";
	public static final String STATUS = "status";
	public static final String WARN = "warn";
	public static final String SUCCESS = "success";
	public static final String ERROR = "error";
	public static final String MESSAGE = "message";
	public static final String CONTENT = "content";
	public static final String PAGECOUNT = "pageCount";

	protected String id;
	protected String[] ids;
	protected Pager pager;
	protected String logInfo;// 日志记录信息
	protected String redirectionUrl;// 操作提示后的跳转URL,为null则返回前一页

	// 产品分类
	protected List<ProductCategory> rootProductCategoryList = null;

	@Resource
	protected MemberService memberService;

	@Resource
	protected NavigationService navigationService;
	@Resource
	protected FriendLinkService friendLinkService;
	@Resource
	protected FooterService footerService;
	@Resource
	protected ProductCategoryService productCategoryService;
	@Resource
	private ProductService productService;
	protected static SystemConfig systemConfig = new SystemConfig();
	protected static final String proxyServer = "27.54.226.163";
	protected static final String proxyPort = "808";
	protected static final String airURI = systemConfig.getAirURI() == null ? "http://203.156.242.124:8088/byc-domflight-server/domFlight.shtml"
			: systemConfig.getAirURI();

//	static {
//		Properties systemProperties = System.getProperties();
//		systemProperties.setProperty("http.proxyHost", proxyServer);
//		systemProperties.setProperty("http.proxyPort", proxyPort);
//	}

	public String input() {
		return null;
	}

	// 获取系统配置信息
	public SystemConfig getSystemConfig() {
		return SystemConfigUtil.getSystemConfig();
	}

	// 获取商品价格货币格式
	public String getPriceCurrencyFormat() {
		return SystemConfigUtil.getPriceCurrencyFormat();
	}

	// 获取商品价格货币格式（包含货币单位）
	public String getPriceUnitCurrencyFormat() {
		return SystemConfigUtil.getPriceUnitCurrencyFormat();
	}

	// 获取订单货币格式
	public String getOrderCurrencyFormat() {
		return SystemConfigUtil.getOrderCurrencyFormat();
	}

	// 获取订单货币格式（包含货币单位）
	public String getOrderUnitCurrencyFormat() {
		return SystemConfigUtil.getOrderUnitCurrencyFormat();
	}

	// 获取当前登录会员，若未登录则返回null
	public Member getLoginMember() {
		String id = (String) getSession(Member.LOGIN_MEMBER_ID_SESSION_NAME);
		if (StringUtils.isEmpty(id)) {
			return null;
		}
		Member loginMember = memberService.load(id);
		return loginMember;
	}

	// 获取Attribute
	public Object getAttribute(String name) {
		return ServletActionContext.getRequest().getAttribute(name);
	}

	// 设置Attribute
	public void setAttribute(String name, Object value) {
		ServletActionContext.getRequest().setAttribute(name, value);
	}

	// 获取Parameter
	public String getParameter(String name) {
		return getRequest().getParameter(name);
	}

	// 获取Parameter数组
	public String[] getParameterValues(String name) {
		return getRequest().getParameterValues(name);
	}

	// 获取Session
	public Object getSession(String name) {
		ActionContext actionContext = ActionContext.getContext();
		Map<String, Object> session = actionContext.getSession();
		return session.get(name);
	}

	// 获取Session
	public Map<String, Object> getSession() {
		ActionContext actionContext = ActionContext.getContext();
		Map<String, Object> session = actionContext.getSession();
		return session;
	}

	// 设置Session
	public void setSession(String name, Object value) {
		ActionContext actionContext = ActionContext.getContext();
		Map<String, Object> session = actionContext.getSession();
		session.put(name, value);
	}

	// 获取Request
	public HttpServletRequest getRequest() {
		return ServletActionContext.getRequest();
	}

	// 获取Response
	public HttpServletResponse getResponse() {
		return ServletActionContext.getResponse();
	}

	// 获取Application
	public ServletContext getApplication() {
		return ServletActionContext.getServletContext();
	}

	// AJAX输出，返回null
	public String ajax(String content, String type) {
		try {
			HttpServletResponse response = ServletActionContext.getResponse();
			response.setContentType(type + ";charset=UTF-8");
			response.setHeader("Pragma", "No-cache");
			response.setHeader("Cache-Control", "no-cache");
			response.setDateHeader("Expires", 0);
			response.getWriter().write(content);
			response.getWriter().flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	// AJAX输出文本，返回null
	public String ajaxText(String text) {
		return ajax(text, "text/plain");
	}

	// AJAX输出HTML，返回null
	public String ajaxHtml(String html) {
		return ajax(html, "text/html");
	}

	public String ajaxPager(String html, String pageCount) {
		Map<String, String> jsonMap = new HashMap<String, String>();
		jsonMap.put(STATUS, WARN);
		jsonMap.put(CONTENT, html);
		jsonMap.put(PAGECOUNT, pageCount);
		JSONObject jsonObject = JSONObject.fromObject(jsonMap);
		return ajaxHtml(jsonObject.toString());
	}

	// AJAX输出XML，返回null
	public String ajaxXml(String xml) {
		return ajax(xml, "text/xml");
	}

	// 根据字符串输出JSON，返回null
	public String ajaxJson(String jsonString) {
		return ajax(jsonString, "text/html");
	}

	// 根据Map输出JSON，返回null
	public String ajaxJson(Map<String, String> jsonMap) {
		JSONObject jsonObject = JSONObject.fromObject(jsonMap);
		return ajax(jsonObject.toString(), "text/html");
	}

	// 输出JSON警告消息，返回null
	public String ajaxJsonWarnMessage(String message) {
		Map<String, String> jsonMap = new HashMap<String, String>();
		jsonMap.put(STATUS, WARN);
		jsonMap.put(MESSAGE, message);
		JSONObject jsonObject = JSONObject.fromObject(jsonMap);
		return ajax(jsonObject.toString(), "text/html");
	}

	// 输出JSON成功消息，返回null
	public String ajaxJsonSuccessMessage(String message) {
		Map<String, String> jsonMap = new HashMap<String, String>();
		jsonMap.put(STATUS, SUCCESS);
		jsonMap.put(MESSAGE, message);
		JSONObject jsonObject = JSONObject.fromObject(jsonMap);
		return ajax(jsonObject.toString(), "text/html");
	}

	// 输出JSON错误消息，返回null
	public String ajaxJsonErrorMessage(String message) {
		Map<String, String> jsonMap = new HashMap<String, String>();
		jsonMap.put(STATUS, ERROR);
		jsonMap.put(MESSAGE, message);
		JSONObject jsonObject = JSONObject.fromObject(jsonMap);
		return ajax(jsonObject.toString(), "text/html");
	}

	public <T> String ajaxJsonList(Collection<T> list) {
		JSONObject jsonObject = JSONObject.fromObject(list);
		return ajax(jsonObject.toString(), "text/html");
	}

	// public<T> String ajaxJsonList(List<T> list)
	// {
	// JSONObject jsonObject = JSONObject.fromObject(list);
	// return ajax(jsonObject.toString(), "text/html");
	// }

	public String ajaxJsonObj(Object obj) {
		JSONObject jsonObject = JSONObject.fromObject(obj);
		return ajax(jsonObject.toString(), "text/html");
	}

	// 设置页面不缓存
	public void setResponseNoCache() {
		getResponse().setHeader("progma", "no-cache");
		getResponse().setHeader("Cache-Control", "no-cache");
		getResponse().setHeader("Cache-Control", "no-store");
		getResponse().setDateHeader("Expires", 0);
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String[] getIds() {
		return ids;
	}

	public void setIds(String[] ids) {
		this.ids = ids;
	}

	public Pager getPager() {
		return pager;
	}

	public void setPager(Pager pager) {
		this.pager = pager;
	}

	public String getLogInfo() {
		return logInfo;
	}

	public void setLogInfo(String logInfo) {
		this.logInfo = logInfo;
	}

	public String getRedirectionUrl() {
		return redirectionUrl;
	}

	public void setRedirectionUrl(String redirectionUrl) {
		this.redirectionUrl = redirectionUrl;
	}

	public List<Navigation> getTopNavigationList() {
		return navigationService.getTopNavigationList();
	}

	public List<Navigation> getMiddleNavigationList() {
		return navigationService.getMiddleNavigationList();
	}

	public List<Navigation> getBottomNavigationList() {
		return navigationService.getBottomNavigationList();
	}

	public List<FriendLink> getFriendLinkList() {
		return friendLinkService.getAll();
	}

	public List<FriendLink> getPictureFriendLinkList() {
		return friendLinkService.getPictureFriendLinkList();
	}

	public List<FriendLink> getTextFriendLinkList() {
		return friendLinkService.getTextFriendLinkList();
	}

	public Footer getFooter() {
		return footerService.getFooter();
	}

	public List<ProductCategory> getRootProductCategoryList() {
		List<ProductCategory> rootProductCategoryList = productCategoryService
				.getRootProductCategoryList();
		for (ProductCategory productCateTemp : rootProductCategoryList) {
			productCateTemp.setBrandList(productService.getBrandList(
					productCateTemp, 0, 10));
		}
		return rootProductCategoryList;

	}

	public String connecteNet(URL url,String requestXml) throws IOException,
			ProtocolException, UnsupportedEncodingException {
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		connection.setDoOutput(true);
		connection.setInstanceFollowRedirects(false);
		connection.setRequestProperty("Content-Type", "application/xml");
		// connection.setRequestProperty("Accept-Charset", "utf-8");
		// connection.setRequestProperty("contentType", "utf-8");
		connection.setRequestMethod("POST");

		OutputStream os = connection.getOutputStream();
		// Write your XML to the OutputStream (JAXB is used in this example)
		os.write(requestXml.getBytes(), 0, requestXml.getBytes().length);
		os.flush();
		connection.getResponseCode();

		InputStream in = connection.getInputStream();
		// readFileByChars(in);
		BufferedReader bin = new BufferedReader(new InputStreamReader(in,
				"utf-8"));
		String inputLine;
		StringBuffer ret =new StringBuffer();
		while ((inputLine = bin.readLine()) != null) {
			ret.append(inputLine+"\r\n");
		}

		bin.close();
		in.close();

		connection.disconnect();
		return ret.toString();
	}

}